package db

import (
	"database/sql"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// Company 定义公司表
type Company struct {
	ID   uint   `gorm:"primaryKey"`
	Name string `gorm:"column:name;not null"`
	// 一个公司可以有多个用户
	Users []User `gorm:"foreignKey:CompanyID"`
}

// User 定义用户表
type User struct {
	ID        uint   `gorm:"primaryKey"`
	Name      string `gorm:"column:name"`
	Email     string `gorm:"column:email"`
	CompanyID uint   `gorm:"column:company_id;not null"` // 外键，指向 Company 的 ID
	// 一个用户属于一个公司
	Company   Company    `gorm:"foreignKey:CompanyID"`
	Languages []Language `gorm:"many2many:user_languages;"`
}

type CreditCard struct {
	gorm.Model
	Number string
	UserID uint
}

type Language struct {
	gorm.Model
	Name string
}

// Product 定义产品表
type Product struct {
	gorm.Model
	Code  string
	Price uint
}

// InitMySQL initializes and returns a GORM DB instance for MySQL.
func InitMySQL() *gorm.DB {
	dsn := "root:123456@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
	sqlDB, err := sql.Open("mysql", dsn)
	if err != nil {
		panic("failed to connect mysql database: " + err.Error())
	}

	gormDB, err := gorm.Open(mysql.New(mysql.Config{
		Conn: sqlDB,
	}), &gorm.Config{
		/*		NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // gorm框架默认数据库表名复数化，该配置能让所有表名都是单数
			},*/
	})
	if err != nil {
		panic("failed to open gorm mysql connection: " + err.Error())
	}

	// 迁移基础表
	gormDB.AutoMigrate(&Company{}, &User{}, &Product{}, &Language{}, &CreditCard{})
	return gormDB
}

// InitSQLite initializes and returns a GORM DB instance for SQLite.
func InitSQLite() *gorm.DB {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect sqlite database: " + err.Error())
	}
	db.AutoMigrate(&Company{}, &User{}, &Product{})
	return db
}
